﻿// Copyright (c) Argo Zhang (argo@163.com). All rights reserved.
// Licensed under the LGPL License, Version 3.0. See License.txt in the project root for license information.
// Website: https://admin.blazor.zone

using BlazorAdmin.Models;
using BlazorAdmin.Interface;
using BootstrapBlazor.Components;
using BlazorAdmin.Web.Shared.Services;
using BlazorAdmin.Web.Shared.Extensions;
using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Components.Forms;
using System.Diagnostics.CodeAnalysis;
using Microsoft.AspNetCore.Hosting;

namespace BlazorAdmin.Web.Shared.Pages.Admin
{
    /// <summary>
    /// 个人中心
    /// </summary>
    public partial class Profiles
    {
        private readonly List<UploadFile> previewFileList = new();
        private readonly List<SelectedItem> apps = new();
        [NotNull] private User? currentUser = null;
        private string? defaultLogoFolder;
        private string? defaultLogo = string.Empty;

        [CascadingParameter]
        [NotNull]
        private Layout? Layout { get; set; }

        /// <summary>
        /// 
        /// </summary>
        protected override void OnInitialized()
        {
            base.OnInitialized();
            currentUser = AppContext.CurrentUser;
            if (null == currentUser)
                return;
            currentUser.Password = ""; //清除用户密码

            List<SelectedItem>? items = DictService.GetApps().ToSelectedItemList();
            if (null != items && items.Count > 0)
                apps.AddRange(items);

            defaultLogo = DictService.GetDefaultIcon();
            defaultLogoFolder = DictService.GetIconFolderPath();

            string? logoFile = currentUser.Icon ?? defaultLogo;

            //string? logoFolder = defaultLogoFolder;
            //string? fileName = Path.Combine(WebHost.WebRootPath, logoFolder.Replace("/", "\\").TrimStart('\\'), logoFile);
            //currentUser.Icon = Path.Combine(logoFolder, logoFile);

            string? fileName = $"wwwroot/{logoFile}"; //{WebHost.WebRootPath.Replace(@"\","/")}
            currentUser.Icon = logoFile;

            if (!File.Exists(fileName))
                return;

            UploadFile? uploadFile = new() { FileName = $"wwwroot/{logoFile}", PrevUrl = currentUser.Icon };
            FileInfo? fileInfo = new(fileName);
            uploadFile.Size = fileInfo.Length;
            previewFileList.Add(uploadFile);
        }

        private async Task ShowToast(bool result, string title, string? content = "保存")
        {
            if (result)
            {
                await ToastService.Success(title, $"{content}{title}成功");
            }
            else
            {
                await ToastService.Error(title, $"{content}{title}失败");
            }
        }

        private async Task OnSaveDisplayName(EditContext context)
        {
            if (null == currentUser)
                return;

            var ret = UserService.SaveDisplayName(currentUser.UserName, currentUser.DisplayName);
            await ShowToast(ret, "显示名称");
            if (ret)
            {
                await RenderLayout("displayName");
            }
        }

        /// <summary>
        /// 保存密码更改
        /// </summary>
        private Task OnSavePassword(EditContext context)
        {
            if (null == currentUser)
                return Task.CompletedTask;

            currentUser.Password = currentUser.Password.Trim();
            currentUser.NewPassword = currentUser.NewPassword.Trim();
            if (currentUser.Password == currentUser.NewPassword)
                return MsgService.Show(new()
                {
                    Icon = "fa-solid fa-circle-info",
                    Content = "新密码不能与原密码相同",
                    Color = Color.Danger
                });

            var success = UserService.ChangePassword(currentUser.UserName, currentUser.Password, currentUser.NewPassword);

            if (!success)
            {
                return MsgService.Show(new()
                {
                    Icon = "fa-solid fa-circle-info",
                    Content = "原密码不正确",
                    Color = Color.Danger
                });
            }
            else
            {
                currentUser.Password = "";
                currentUser.NewPassword = "";
                currentUser.ConfirmPassword = "";

                return ShowToast(success, "密码");
            }
        }

        private async Task OnSaveApp()
        {
            if (null == currentUser)
                return;

            var ret = UserService.SaveApp(AppContext.LoginName, currentUser.App);
            await ShowToast(ret, "默认应用");
        }

        private async Task OnSaveIcon(UploadFile file)
        {
            if (null == currentUser)
                return;

            // 保存到物理文件
            var logoFile = $"{currentUser.UserName}{Path.GetExtension(file.OriginFileName)}";
            var fileName = WebHost.CombineLogoFile(defaultLogoFolder, logoFile);
            if (File.Exists(fileName))
            {
                File.Delete(fileName);
            }

            // 文件大小 10 M
            bool ret = false;

            //Linux环境下保存文件时，无法识别路径符号："\\"，需要转换成"/"才能识别，否则整个路径会被当做文件夹名称
            if (OperatingSystem.IsLinux())
                ret = await file.SaveToFileAsync(fileName.Replace("\\", @"/"), 10 * 1024 * 1000);
            else
                ret = await file.SaveToFileAsync(fileName, 10 * 1024 * 1000);

            // 更新用户信息
            if (ret)
            {
                ret = UserService.SaveLogo(currentUser.UserName, logoFile);

                currentUser.Icon = Path.Combine(defaultLogoFolder, logoFile);
                previewFileList.Clear();
                previewFileList.Add(new UploadFile()
                {
                    PrevUrl = $"{currentUser.Icon}?v={DateTime.Now.Ticks}",
                    Size = file.Size,
                    FileName = logoFile
                });
            }
            await ShowToast(ret, "用户头像");
        }

        private async Task<bool> OnDeleteIcon(UploadFile file)
        {
            if (null == currentUser)
                return false;

            var ret = false;
            var logoFile = file.FileName;
            if (!string.IsNullOrEmpty(logoFile))
            {
                var fileName = WebHost.CombineLogoFile(defaultLogoFolder, logoFile);
                if (!logoFile.Equals(defaultLogo, StringComparison.OrdinalIgnoreCase) && File.Exists(fileName))
                {
                    File.Delete(fileName);
                }
                ret = UserService.SaveLogo(currentUser.UserName, null);
            }
            await ShowToast(ret, "用户头像", "删除");
            return ret;
        }

        private async Task RenderLayout(string key)
        {
            if (null == Layout.OnUpdateAsync)
                return;

            await Layout.OnUpdateAsync(key);
        }

        #region Inject

        [Inject]
        private BootstrapAppContext? AppContext { get; set; }

        [Inject]
        private IDict? DictService { get; set; }

        [Inject]
        private IUser? UserService { get; set; }

        [Inject]
        private ToastService? ToastService { get; set; }

        [Inject]
        private IWebHostEnvironment? WebHost { get; set; }

        [Inject]
        private MessageService? MsgService { get; set; }

        #endregion
    }
}